<template>
  <div
    ref="content"
    class="contentBox setScrollbar"
  >
    <el-row slot="extra">
      <el-button-group style="display: flex;justify-content: center;margin: 10px 20px;">
        <el-button
          type="primary"
          icon="el-icon-upload"
          size="mini"
          @click="submit"
        >
          上传
        </el-button>
        <el-button
          icon="el-icon-arrow-left"
          size="mini"
          style="margin-left: 20px;"
          @click="rb"
        >
          返回
        </el-button>
      </el-button-group>
    </el-row>
    <el-row>
      <div
        ref="canvas"
        class="canvas"
      />
      <div
        id="js-properties-panel"
        class="panel"
      />
    </el-row>
    <el-dialog
      v-if="modalFormAddVisible"
      title="表单设计"
      :visible.sync="modalFormAddVisible"
      width="90%"
      center
    >
      <form-making
        ref="formDesgin"
        @getFormJsonScript="select"
      />
    </el-dialog>
    <el-dialog
      v-if="modalUserAddVisible"
      title="人员选择"
      :visible.sync="modalUserAddVisible"
      width="60%"
      center
    >
      <person-select
        ref="personSelect"
        :selected-data="selectedData"
        @selectData="selectUser"
      />
    </el-dialog>
    <el-dialog
      v-if="modalStationAddVisible"
      title="岗位选择"
      :visible.sync="modalStationAddVisible"
      width="60%"
      center
    >
      <role-select
        ref="personSelect"
        :selected-data="selectedData"
        @selectData="selectUser"
      />
    </el-dialog>
  </div>
</template>

<script>
// 引入相关的依赖
// import BpmnViewer from 'bpmn-js'
import {emptyProcessXml} from '@/components/bpmn/utils/constant';
import BpmnModeler from 'bpmn-js/lib/Modeler';
import propertiesPanelModule from 'bpmn-js-properties-panel';
import propertiesProviderModule from '@/components/bpmn'
import camundaModdleDescriptor from 'camunda-bpmn-moddle/resources/camunda';
/* 左边工具栏以及编辑节点的样式 */
import 'bpmn-js/dist/assets/diagram-js.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css';
/* 右边工具栏样式 */
import 'bpmn-js-properties-panel/dist/assets/bpmn-js-properties-panel.css';
import zhCN from '@/components/bpmn/utils/customTranslate';
import Vue from 'vue'
import FormMaking from '@/components/Form/ext/FormMaking';
import personSelect from './components/personSelect';
import roleSelect from './components/roleSelect';
import { deployment,getProcessDefinitionKeyXml } from '@/api/bpmn/bpmn'
const customTranslate = {
  translate: ['value', zhCN]
};
export default {
  name: '',
  components: { FormMaking,personSelect,roleSelect },
  props:{
    defName: {
      type: String,
      default: ''
    },
    defKey: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: 'create'
    }
  },
  data() {
    return {
      // bpmn建模器
      bpmnModeler: null,
      container: null,
      modalFormAddVisible: false,
      canvas: null,
      selectedData:'',
      modalStationAddVisible:false,
      modalUserAddVisible:false
    };
  },
  // 计算属性
  computed: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  // 生命周期 - 载入后, Vue 实例挂载到实际的 DOM 操作完成，一般在该过程进行 Ajax 交互
  mounted() {
    this.init();
  },
  // 方法集合
  methods: {
    open(e,select){
      console.log('ddddddddddddddddddd')
      this.$nextTick(()=>{
        if(select === 'person'){
          console.log(this.dom.value)
          this.$refs.personSelect.queryUser(this.dom.value);
        }
      })
    },
    init() {
      Vue.prototype.bpmn = []
      if (this.bpmnModeler) {
        this.bpmnModeler.get('moddle').ids.clear()
        document.querySelector('#canvas').innerHTML = ''
        document.querySelector('#js-properties-panel').innerHTML = ''
      }
      // 获取到属性ref为“canvas”的dom节点
      const canvas = this.$refs.canvas;
      // 建模
      this.bpmnModeler = new BpmnModeler({
        container: canvas,
        //添加控制板
        propertiesPanel: {
          parent: '#js-properties-panel'
        },
        additionalModules: [
          // 左边工具栏以及节点
          propertiesProviderModule,
          // 右边的工具栏
          propertiesPanelModule,
          // 中文
          customTranslate
        ],
        moddleExtensions: {
          camunda: camundaModdleDescriptor
        }
      });
      this.refreshDiagram(this.bpmnModeler);
    },
    refreshDiagram(bpmnModeler, editJsonData) {
      const self = this
      document
        .getElementsByClassName('bjs-container')[0]
        .removeChild(document.getElementsByClassName('bjs-powered-by')[0]) // 移除logo
      if (editJsonData) {
        self.bpmnModeler.importXML(editJsonData, function(err) {
          if (!err) {
            self.attachEvent()
            const eventBus = self.bpmnModeler.get('eventBus')
            const events = ['selection.changed']
            events.forEach(function(event) {
              eventBus.on(event, function(e) {
                self.attachEvent(e)
              })
            })
            document.querySelector('#camunda-name').setAttribute('readOnly', true)
          }
        })
      } else if (self.defKey) {
        getProcessDefinitionKeyXml(self.defKey).then(res => {
          self.bpmnModeler.importXML(res.bpmn20Xml, function(err) {
            if (!err) {
              self.attachEvent()
              const eventBus = self.bpmnModeler.get('eventBus')
              const events = ['selection.changed']
              events.forEach(function(event) {
                eventBus.on(event, function(e) {
                  self.attachEvent(e)
                })
              })
              const process = Vue.prototype.bpmn.find(item => {
                return item.type === 'bpmn:Process'
              })
              process.businessObject.name = self.defName
              document.querySelector('#camunda-name').setAttribute('readOnly', true)
            }
          })
        })
      }else {
        const processXml = emptyProcessXml()
        self.bpmnModeler.importXML(processXml, function(err) {
          if (!err) {
            self.attachEvent();
            const eventBus = self.bpmnModeler.get('eventBus');
            const events = ['selection.changed'];
            events.forEach(function(event) {
              eventBus.on(event, function(e) {
                self.attachEvent(e);
              });
            });
            const process = Vue.prototype.bpmn.find(item => {
              return item.type === 'bpmn:Process'
            })
            process.businessObject.name = self.defName
            document.querySelector('#camunda-name').setAttribute('readOnly', true)
          } else {
            console.log(processXml)
            console.error('error:', err)
          }
        })
      }
    },
    attachEvent(e) {
      const self = this;
      if (!e) {
        // 初始化
        // self.addProcessEvent();
      } else {
        // 页面点击事件
        if (e.newSelection.length === 0) {
          // 点击空白地方 展示位process
          if (e.oldSelection.length === 0) {
            // 一直点击空白地方 不需要重复添加事件
            // do nothing
          } else {
            // 添加 candidateStarterGroups candidateStarterUsers 点击事件
            // self.addProcessEvent();
          }
        } else {
          // 有选择项
          const selection = e.newSelection[0];
          if (selection.type === 'bpmn:UserTask') {
            // 人工任务
            self.addUserTaskEvent();
            self.addFormDesignerEvent();
          } else if (selection.type === 'bpmn:StartEvent') {
            self.addFormDesignerEvent();
          }
        }
      }
    },
    addFormDesignerEvent() {
      const self = this;
      self.formDesigner = document.querySelector('#camunda-form-key');
      const selectFormBtn = this.createSelectButton();
      self.formDesigner.parentElement.appendChild(selectFormBtn);
      selectFormBtn.addEventListener('click', () => {
        self.openFormModel(self.formDesigner);
      });
    },
    addProcessEvent() {
      const self = this;
      self.candidateStarterUsers = document.querySelector(
        '#camunda-candidateStarterUsers'
      );
      const selectStartUsersBtn = this.createSelectButton();
      self.candidateStarterUsers.parentElement.appendChild(selectStartUsersBtn);
      selectStartUsersBtn.addEventListener('click', () => {
        self.openUserModel(self.candidateStarterUsers);
      });

      self.candidateStarterGroups = document.querySelector(
        '#camunda-candidateStarterGroups'
      );
      const selectStartGroupsBtn = this.createSelectButton();
      self.candidateStarterGroups.parentElement.appendChild(
        selectStartGroupsBtn
      );
      selectStartGroupsBtn.addEventListener('click', () => {
        self.openStationModel(self.candidateStarterGroups);
      });
    },
    addUserTaskEvent() {
      const self = this;
      self.assignee = document.querySelector('#camunda-assignee');
      const selectAssigneeBtn = this.createSelectButton();
      self.assignee.parentElement.appendChild(selectAssigneeBtn);
      selectAssigneeBtn.addEventListener('click', () => {
        self.inputValue = document.querySelector('#camunda-assignee').value;
        self.openUserModel(self.assignee);
      });

      // 候选用户
      self.candidateUsers = document.querySelector('#camunda-candidateUsers');
      const selectUsersBtn = this.createSelectButton();
      self.candidateUsers.parentElement.appendChild(selectUsersBtn);
      selectUsersBtn.addEventListener('click', () => {
        self.inputValue = document.querySelector('#camunda-candidateUsers').value;
        self.openUserModel(self.candidateUsers);
      });

      // 候选组选择
      self.candidateGroups = document.querySelector('#camunda-candidateGroups');
      const selectGroupsBtn = this.createSelectButton();
      self.candidateGroups.parentElement.appendChild(selectGroupsBtn);
      selectGroupsBtn.addEventListener('click', () => {
        self.openStationModel(self.candidateGroups);
      });
    },
    // 打开用户配置界面
    openUserModel(obj) {
      const self = this;
      self.modalUserAddVisible = true;
      self.dom = obj;
      self.selectedData = this.dom.value
    },
    // 打开角色配置界面
    openStationModel(obj) {
      const self = this;
      self.modalStationAddVisible = true;
      self.dom = obj;
    },
    // 打开表单配置界面
    openFormModel(obj) {
      const self = this;
      self.modalFormAddVisible = true;
      self.dom = obj;
      if (obj.value) {
        setTimeout(() => {
          console.log(JSON.parse(obj.value))
          this.$refs.formDesgin.initWidgetForm(JSON.parse(obj.value));
        }, 500);
      }
    },
    createSelectButton() {
      const selectBtn = document.createElement('button');
      const txt = document.createElement('span');
      txt.innerText = '+';
      /*
      display: inline-block;
      line-height: 13px;
      position: relative;
      top: -3px;
      width: 100%;
      height: 20px;
      */
      txt.style.position = 'relative';
      txt.style.display = 'inline-block';
      txt.style.top = '-2px';
      txt.style.width = '100%';
      txt.style.lineHeight = '13px';
      txt.style.height = '20px';
      selectBtn.type = 'button';
      selectBtn.className = 'el-button el-button--mini selecter';
      selectBtn.appendChild(txt);
      selectBtn.style.width = '48px';
      selectBtn.style.right = '3px';
      selectBtn.style.height = '20px';
      selectBtn.style.top = '2px';
      return selectBtn;
    },
    success() {
      // console.log('创建成功!')
      this.addEventBusListener();
    },
    select(data) {
      const self = this
      if (typeof data === 'object') {
        data = JSON.stringify(data)
      }
      const elements = Vue.prototype.bpmn.filter(item => {
        return item.id === document.querySelector('#camunda-id').value
      })
      if (elements.length > 0) {
        const element = elements[0]
        element.businessObject[self.dom.name] = data
        self.dom.value = data
        self.modalUserAddVisible = false
        self.modalStationAddVisible = false
        self.modalFormAddVisible = false
      }
    },
    selectUser(data) {
      const self = this
      const elements = Vue.prototype.bpmn.filter(item => {
        return item.id === document.querySelector('#camunda-id').value
      })
      if (elements.length > 0) {
        const element = elements[0]
        element.businessObject[self.dom.name] = data.code
        self.dom.value = data.code
        self.modalUserAddVisible = false
        self.modalStationAddVisible = false
        self.modalFormAddVisible = false
      }
    },
    post_selectUser(data){
      const self = this
      const elements = Vue.prototype.bpmn.filter(item => {
        return item.id === document.querySelector('#camunda-id').value
      })
      if (elements.length > 0) {
        const element = elements[0]
        element.businessObject[self.dom.name] = data.id
        self.dom.value = data.id
        self.modalUserAddVisible = false
        self.modalStationAddVisible = false
        self.modalFormAddVisible = false
      }
    },
    handleCancel(){
      this.modalUserAddVisible = false
      this.modalStationAddVisible = false
      this.modalFormAddVisible = false
    },
    submit() {
      const self = this
      const processes = Vue.prototype.bpmn.filter(item => {
        return item.type === 'bpmn:Process'
      })

      if (processes.length > 0) {
        const process = processes[0]
        if (!process.businessObject.isExecutable) {
          this.$message.error('请勾选流程可执行');
          return
        }

        if (!process.businessObject.name) {
          this.$message.error('请输入流程名称');
          return
        }

        this.bpmnModeler.saveXML((err, xml) => {
          if (err) {
            return
          }

          const option = {
            'procdef-name': process.businessObject.name,
            'procdef-xml': xml
          }
          deployment(option).then(res => {
            self.$message({
              message: `配置流程-${process.businessObject.name}-成功`,
              type: 'success',
              duration: 1500
            })
            self.$emit('callData', res.deployedProcessDefinitions)
          })
        })
      }
    },
    clean() {
      const self = this
      const elements = Vue.prototype.bpmn.filter(item => {
        return item.id === document.querySelector('#camunda-id').value
      })
      if (elements.length > 0) {
        const element = elements[0]
        if (element.businessObject.hasOwnProperty(self.dom.name)) {
          delete element.businessObject[self.dom.name]
        }
        self.dom.value = ''
        self.modalUserAddVisible = false
        self.modalStationAddVisible = false
        self.modalFormAddVisible = false
      }
    },
    rb() {
      this.$emit('cb')
    },
    addEventBusListener() {
      // 监听 element
      const eventBus = this.bpmnModeler.get('eventBus');
      const eventTypes = [
        'element.click',
        'element.changed',
        'element.updateLabel'
      ];
      eventTypes.forEach(function(eventType) {
        eventBus.on(eventType, function(e) {
          if (!e || e.element.type == 'bpmn:Process') return;
          if (eventType === 'element.changed') {
            // that.elementChanged(e)
          } else if (eventType === 'element.click') {
            // if (e.element.type === 'bpmn:Task') {
            // }
          } else if (eventType === 'element.updateLabel') {
            console.log('element.updateLabel', e.element);
          }
        });
      });
    }
  }
};
</script>

<style scoped>
.containers {
  background-color: #ffffff;
  width: 100%;
  height: calc(100vh - 52px);
}
.canvas {
  width: 100%;
  height: 100%;
  min-height: 800px;
  display: table;
}
.panel {
  position: absolute;
  right: 0;
  top: 0;
  width: 300px;
  background-color: #f8f8f8;
}
</style>

<style lang="less" scoped>
  .contentBox{
    padding: 0px;
  }
  /deep/.bpp-properties-panel input, .bpp-properties-panel button, .bpp-properties-panel textarea, .bpp-properties-panel [contenteditable]{
    padding:0px !important;
    line-height: 1 !important;
  }
</style>
